package master选举.curator实现;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.retry.ExponentialBackoffRetry;


public class Recipes_MasterSelect {
    static String master_path = "/curator";
//    Leader Election方式 完成操作就释放master节点

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 10; i++) {
            CuratorFramework client = CuratorFrameworkFactory.builder()
                    .connectString("192.168.0.201:2181,192.168.0.203:2181,192.168.0.204:2181")
                    .sessionTimeoutMs(5000)
                    .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                    .namespace("base")
                    .build();
            client.start();
            System.out.println(client.toString()+"上线");

            LeaderSelector selector = new LeaderSelector(client, master_path, new LeaderSelectorListenerAdapter() {
                public void takeLeadership(CuratorFramework client) throws Exception {
                    System.out.println(client.toString()+"成为Master角色");
                    Thread.sleep(3000);
                    System.out.println(client.toString()+"完成Master操作，释放Master权利");
                }
            });
            selector.autoRequeue();
            selector.start();
        }

        Thread.sleep(100000);
    }
}

